package com.yunliuchain.examination.security.interceptor;

import com.yunliuchain.examination.common.constant.MsgCode;
import com.yunliuchain.examination.common.context.LoginUserContext;
import com.yunliuchain.examination.common.res.ApiResult;
import com.yunliuchain.examination.security.cache.LoginUserCache;
import com.yunliuchain.examination.system.res.UserRes;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;


@Component
public class UserLoginInterceptor extends HandlerInterceptorAdapter {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private LoginUserCache userCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("UserLoginInterceptor .....");
//        String token = request.getHeader(Global.X_ACCESS_TOKEN) ;
//        if(StringUtils.isBlank(token))
//            token = request.getParameter(Global.X_ACCESS_TOKEN);
//        if(StringUtils.isBlank(token)){
//           output(response);
//           return false;
//        }
//        UserRes userRes = userCache.get(Global.ASS_TOKEN + token);
//        if(userRes == null){
//            output(response);
//            return false;
//        }
        UserRes user = new UserRes();
        user.setUserId(1l);
        user.setLoginName("admin");
        user.setRealName("管理员");
        user.setIsAdmin(true);
        user.setCompanyId(1l);
        LoginUserContext.setCurrent(user);
        return true;
    }


    private void output(HttpServletResponse response) {
        response.setContentType("json/application; charset=UTF-8");
        OutputStream writer = null;
        try {
            writer = response.getOutputStream();
            ApiResult apiResult = ApiResult.fail("请先登录");
            apiResult.setCode(MsgCode.NO_LOGIN);
            writer.write(apiResult.toString().getBytes("utf-8"));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
